package com.coocaa.ops.admin.base.aspect;

import com.coocaa.ops.admin.async.log.model.LogInfoModel;
import com.coocaa.ops.admin.async.log.service.LogRecordServiceImpl;
import com.coocaa.ops.admin.base.util.WebUtil;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bijiahao
 * @date : 2019/7/18.
 * @description 操作日志切面
 */
@Slf4j
@Component
@Aspect
public class OpLogAspect {

    @Autowired
    private LogRecordServiceImpl logRecordService;

    @Pointcut("@annotation(com.coocaa.ops.admin.base.annotation.Auth)")
    public void opLogPointcut() {

    }

    /**
     * 日志操作切面处理
     *
     * @param proceedingJoinPoint
     * @param
     */
    @Around(value = "opLogPointcut()")
    public Object opLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        Object returnValue = proceedingJoinPoint.proceed();
        Long end = System.currentTimeMillis();
        long costTime = end - begin;
        SysUserEntity userEntity = this.getUserForLogOp();
        if (null != userEntity) {
            logRecordService.logOpRecord(LogInfoModel.getLogInfoModel(proceedingJoinPoint, costTime, returnValue, userEntity));
        }
        return returnValue;
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    private SysUserEntity getUserForLogOp() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        if (null == request) {
            return null;
        }
        SysUserEntity userEntity = WebUtil.getUserForLogOpRecord(request);
        return userEntity;
    }
}
